//1.创建路由组件
import Vue from 'vue'
import VueRouter from 'vue-router'
import Main from "../views/Main.vue"
import Cookie from 'js-cookie'

// 将路由与组件进行映射
Vue.use(VueRouter)
//创建router实例
const router = new VueRouter({
    routes: [
        {
            path: '/',
            component: Main,
            name: 'Main',
            redirect: '/home',
            children: [
                // { path: 'home', name: 'home', component: ()=>import('../views/Home.vue') },
                // { path: 'user', name: 'user', component: User },
                // { path: 'mall', name: 'mall', component: Mall },
                // { path: 'page1', name: 'page1', component: PageOne },
                // { path: 'page2', name: 'page2', component: PageTwo }
            ]
        },
        {
            path: '/login',
            name: 'login',
            component: () => import('../views/Login.vue')
        }

    ]
    //routes:routes
})

//添加全局前置导航守卫
router.beforeEach((to, from, next) => {
    //判断token存不存在
    const token = Cookie.get('token')
    //token不存在，说明当前用用户是未登录，应该跳转至登录页
    if (!token && to.name !== 'login') {
        next({ name: 'login' })
    } else if (token && to.name === 'login') {
        //token存在，说明用户登录，此时跳转至首页
        next({ name: 'home' })
    } else {
        next()
    }
})

export default router

